import socket
import time
import sys

def tcp_server(cmd):
    host = '0.0.0.0'  # 监听所有可用的接口
    port = 9999

    # 创建一次 server之后退出
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)

    try:
        client_socket, addr = server_socket.accept()
    except:
        server_socket.close()
        return

    client_socket.sendall(cmd.encode('utf-8'))
    count = 0
    string = ""
    # 等待回复 “OK”字符串，期间可能会收到心跳检测的信息，需要过滤
    while (count < 100):
        response = client_socket.recv(1024)
        string += response.decode('utf-8').replace("HEARTBEAT", '')
        if (string == "ok"):
            break
        count = count + 1
        time.sleep(0.05)
    client_socket.close()
    server_socket.close()
    time.sleep(0.05) # 短时间多次进行tcp服务创建，会导致 bind 函数失败，需要有延迟

def main():
    # sys.argv[0] 是脚本名称，所以参数从 sys.argv[1] 开始
    if len(sys.argv) > 1:
        param = sys.argv[1]
        tcp_server(param)
    else:
        sys.exit(1)  # 退出代码1表示有错误发生

if __name__ == "__main__":
    main()

